import {
	Platform,
	DatePickerIOS,
	DatePickerAndroid,
	PixelRatio
} from 'react-native';

import {NavigationActions} from 'react-navigation';

var Dimensions = require('Dimensions');

var Common = {};
//url
Common.url = 'http://118.123.13.251:8012/';

//token
Common.token = '';
//获取设备宽高
Common.screenWidth = Dimensions.get('window').width;
Common.screenHeight = Dimensions.get('window').height;
//日期
Common.formatDate = function (date, fmt) {
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}
//时间戳转时间格式
Common.date = function (timestamp, long) {
	var time = new Date(timestamp);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	if (long) {
		return y + '-' + Common.toDou(m) + '-' + Common.toDou(d) + ' ' + Common.toDou(h) + ':' + Common.toDou(mm) + ':' + Common.toDou(s);
	} else {
		return y + '-' + Common.toDou(m) + '-' + Common.toDou(d);
	}

}
//补0
Common.toDou = function (n) {
	return n < 10 ? '0' + n : n;
}
//fetch——POST
Common.ajaxPost = function (url, callback, param, prop) {
	var config = {
		method: 'POST',
		headers: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			'credentials': 'include'
		},
		credentials: 'include'
	}
	if (param) {
		config["body"] = JSON.stringify(param);
	}

	fetch(url, config).then((response) => response.json()).then(
		(json) => {
			if(json.status == 401){
				prop.navigation.navigate('Login');
			}
			else{
				callback(json)
			}
		}
	)
};
//fetch——GET
Common.ajaxGet = function (url, callback, param, prop) {
	var config = {
		method: 'GET',
		headers: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			'credentials': 'include'
		}
	}
	if (param && url.length > 0) {
		url += url.indexOf("?") == -1 ? "?" : "&";
		for (var key in param) {
			url += key + "=" + param[key] + "&";
		}
		url = url.substring(0, url.length - 1);
	}

	fetch(url, config).then((response) => response.json()).then(
		(json) => {
			if(json.status == 401){
				prop.navigation.navigate('Login');
			}
			else{
				callback(json)
			}
		}
	)
};
//DatePicker
Common.showPicker = async function (type, options) {
	if (Platform.OS === 'ios') {
		this.setState({
			type: type,
			showDate: true,
			sHeight: Common.screenHeight
		});
	} else {
		try {
			const {action, year, month, day} = await DatePickerAndroid.open({
				// 要设置默认值为今天的话，使用`new Date()`即可。
				// 下面显示的会是2020年5月25日。月份是从0开始算的。
				date: new Date().setDate(1)
			});
			if (action !== DatePickerAndroid.dismissedAction) {
				// 这里开始可以处理用户选好的年月日三个参数：year, month (0-11), day
				var monthText = month + 1;
				if (monthText < 10) {
					monthText = "0" + monthText;
				}
				var dayText = day;
				if (dayText < 10) {
					dayText = "0" + dayText;
				}
				if (type == 'start') {
					this.setState({
						startDate: year + '-' + monthText + '-' + dayText
					});
				}
				if (type == 'end') {
					this.setState({
						endDate: year + '-' + monthText + '-' + dayText
					});
				}
			}
		} catch ({code, message}) {
			console.warn('Cannot open date picker', message);
		}
	}
}
//循环json，删不要的key
Common.map = function (data, callback, escaped) {
	var object = JSON.parse(JSON.stringify(data));

	if (escaped) {
		if (typeof(escaped) == "object") {
			escaped.map((v) => {
				delete object[v];
			})
		}

		if (typeof(escaped) == "string") {
			delete object[escaped];
		}
	}

	return Object.keys(object).map(callback);
};
//
Common.createHTML = function (array) {
	return array.map((html) => {
		return html;
	})
}

Common.timeago = function (dateTimeStamp) {   //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
	var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
	var hour = minute * 60;
	var day = hour * 24;
	var week = day * 7;
	var halfamonth = day * 15;
	var month = day * 30;
	var now = new Date().getTime();   //获取当前时间毫秒
	console.log(now)
	var diffValue = now / 1000 - dateTimeStamp / 1000;//时间差
	var result = "";

	if (diffValue < 0) {
		return;
	}
	var minC = diffValue / minute;  //计算时间差的分，时，天，周，月
	var hourC = diffValue / hour;
	var dayC = diffValue / day;
	var weekC = diffValue / week;
	var monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		var datetime = new Date();
		datetime.setTime(dateTimeStamp);
		var Nyear = datetime.getFullYear();
		var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}



module.exports = Common;
